package poi;

import java.awt.Color;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * @author xiajiajia
 * 
 */
public class Write2 {
	private XSSFWorkbook wb = null;
	private File xlsx = new File("E:/报表.xlsx");

	public Write2() {
		if (wb == null) {
			wb = new XSSFWorkbook();
		}
	}

	public static void main(String[] args) throws IOException {
		Write2 w = new Write2();
		w.CreateSheet();
	}

	public void CreateSheet() throws IOException {
		int temp1 = 1;
		int temp2 = 1;
		int temp3 = 1;
		int temp4 = 1;

		XSSFSheet sheet = wb.createSheet("test");
		wb.setSheetName(0, "test");
		XSSFRow row = sheet.createRow(0);
		sheet.createFreezePane(0, 1);
		cteateCell(wb, row, 0, "邮箱");
		cteateCell(wb, row, 1, "所在部门");
		cteateCell(wb, row, 2, "部门代码");
		cteateCell(wb, row, 3, "姓名");
		for (int i = 1; i < 5; i++) {
			XSSFRow row2 = sheet.createRow(i);
			// 改为从数据库中读出
			String valu1 = "a@b.com--" + RandomDemo.getRandomPW();
			String valu2 = "中央公司--" + RandomDemo.getRandomPW();
			String valu3 = "1234--" + RandomDemo.getRandomPW();
			String valu4 = "二猫猫--" + RandomDemo.getRandomPW();

			temp1 = Math.max(temp1, valu1.getBytes().length);
			temp2 = Math.max(temp2, valu2.getBytes().length);
			temp3 = Math.max(temp3, valu3.getBytes().length);
			temp4 = Math.max(temp4, valu4.getBytes().length);
			
			cteateCell(wb, row2, 0, valu1);
			cteateCell(wb, row2, 1, valu2);
			cteateCell(wb, row2, 2, valu3);
			cteateCell(wb, row2, 3, valu4);
		}

		sheet.setColumnWidth(0, Math.min(temp1+1, 255) * 256);
		sheet.setColumnWidth(1, Math.min(temp2+1, 255) * 256 );
		sheet.setColumnWidth(2, Math.min(temp3+1, 255) * 256);
		sheet.setColumnWidth(3, Math.min(temp4+1, 255) * 256);

		CellRangeAddress index = new CellRangeAddress(1, 2, 0, 0);//合并单元格: 行 行 列 列
		sheet.addMergedRegion(index);

		FileOutputStream fileOut = new FileOutputStream(xlsx);
		wb.write(fileOut);
		fileOut.close();
		String cmd = "cmd /c start E:/报表.xlsx";
		Runtime.getRuntime().exec(cmd);
	}

	private void cteateCell(XSSFWorkbook wb2, XSSFRow row, int column,
			String value) {
		XSSFCell cell = row.createCell(column);
		cell.setCellValue(value);
		XSSFCellStyle cellstyle = wb.createCellStyle();
		cellstyle.setAlignment(XSSFCellStyle.ALIGN_LEFT);
		cell.setCellStyle(cellstyle);
	}
}
